package com.nami.ucenter.domain.service;

import cn.hutool.json.JSONUtil;
import com.nami.gate.external.basic.constants.DownTopicConst;
import com.nami.gate.external.basic.request.down.DownMsgLogout;
import com.nami.im.network.model.enums.protocol.CMDEnum;
import com.nami.ucenter.domain.port.publisher.DomainEventPublisher;
import com.nami.ucenter.domain.port.repository.CacheUserRepository;
import com.nami.ucenter.domain.port.repository.PacketFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class LogoutDomainService {

    private final CacheUserRepository cacheUserDomainService;
    private final DomainEventPublisher eventPublisher;
    private final PacketFactory packetFactory;

    /**
     * TODO 是否迁移至下发服务，统一发送？ 链路会变长
     *
     * @param
     * @date 2025-02-11
     */
    public void publishLogoutEvent(String sessionId, String mqTags) {
        DownMsgLogout resp = new DownMsgLogout();
        resp.setSessionId(sessionId);
        resp.setPacket(packetFactory.newDownmsgSuccPacket(CMDEnum.DISCONNECT.getCode(), "success"));
        eventPublisher.publish(DownTopicConst.LOGOUT_TOPIC, mqTags, JSONUtil.toJsonStr(resp));
    }


    public boolean terminateOnlineSession(String appKey, String userId, String deviceType) {
        return cacheUserDomainService.removeOnlDevice(appKey, userId, deviceType);
    }

}
